import { forwardRef, useState, useEffect, useImperativeHandle, useRef, useMemo } from 'react'
import { InbizIcon } from '@inbiz/utils';
import { TextWidget, getMessage } from '@inbiz/react';
import { Form, Checkbox } from 'antd'
import EformMemberSelect from '@components/form/grade/EformMemberSelect/preview/web'
import FormItemTitle from '../components/FormItemTitle'
import BelongDirectory from '@inbiz/basic/BelongDirectory';
import './index.less'

const buildInkeys = ['belongCategory', 'matchtype', 'sourceUser']
export default forwardRef(function BuildInArea(props: any, ref) {
  const { config, ShowPlugin, $params, $showAuthority, $categoryData, $selected, permtypeRef, $buildInSearchParams, $fileSearchType,
    categoryLevel, params, searchEngineData, configEvents, engineProps, showTeam, showPerson, belongCategoryRef, getMetaSearchArr, buildInSearchParams } = props

  const [form] = Form.useForm()
  const [userType, $userType] = useState('0')
  const [clearpath, $clearpath] = useState(false)
  const [clearSearchFields, $clearSearchFields] = useState(false)
  const categoryRef = useRef()
  const [memberState, $memberState] = useState(0)
  const [pathValue, $pathValue] = useState({ value: '' })
  const plainOptions = [
    { label: getMessage('SearchResultEngine.name'), value: 'filename' },
    { label: getMessage('SearchResultEngine.content'), value: 'filecontent' },
    { label: getMessage('SearchResultEngine.label'), value: 'filetag' },
  ]

  const initmetadataitems = () => {
    const orignmetaData = searchEngineData.metaData
    if (orignmetaData && (orignmetaData?.file || orignmetaData?.folder)) {
      const metaData = config.IndexName == 'file' ? orignmetaData.file : orignmetaData.folder
      const path = metaData.find(ele => ele.key.toLowerCase() == 'filepath' || ele.key.toLowerCase() == 'folderpath')
      if (path) {
        $pathValue(path)

        setTimeout(() => {
          form.setFieldsValue({
            [path.key.toLowerCase()]: path
          })
          $clearpath(true)
        }, 50)
      }
    } else {
      $pathValue({ value: '' })
    }
  }

  const setAutority = (parentTopFolderId) => {
    if (parentTopFolderId == '7' || parentTopFolderId == engineProps.inbiz.userInfo.topPersonalFolderId) {
      $showAuthority(false)
    } else {
      $showAuthority(true)
    }
  }

  const onValuesChange = (type?: string) => {
    const sourceType = type ?? userType
    const changedValues = form.getFieldsValue()
    let folderid = '', fpath = []
    if (changedValues.folderpath && changedValues.folderpath.value || changedValues.filepath && changedValues.filepath.value) {
      folderid = changedValues.filepath?.value[0].folderid || changedValues.folderpath?.value[0].folderid

      fpath = changedValues.filepath?.folderPath || changedValues.folderpath?.folderPath || ''
      if (fpath) {
        fpath = fpath.split('\\')
      }
    }
    const showAuthority = fpath.includes('1') || !fpath.length
    if (!showAuthority) {
      permtypeRef.current?.resetAll?.()
    }
    // 点击重置和清空是判断是否显示权限, 个人和团队不显示
    if (searchEngineData.parentTopFolderId) {
      setAutority(searchEngineData.parentTopFolderId)
    } else {
      $showAuthority(showAuthority)
    }

    const keyArray = Object.keys(changedValues).filter(item => changedValues[item] && item !== 'SearchFields')
    let path = '', sourceUser = ''
    for (let index = 0; index < keyArray.length; index++) {
      const key = keyArray[index];
      let value = changedValues[key]
      if (key == 'sourceuser' && value.length > 0) {
        if (sourceType == '0') {
          if (config.IndexName == 'file') {
            sourceUser = `(filecreateoperator:(${value[0].identityid}) OR filemodifyoperator:(${value[0].identityid}))`
          } else {
            sourceUser = `(foldercreateoperator:(${value[0].identityid}) OR foldermodifyoperator:(${value[0].identityid}))`
          }
        } else if (sourceType == '1') {
          if (config.IndexName == 'file') {
            sourceUser = `filecreateoperator:(${value[0].identityid})`
          } else {
            sourceUser = `foldercreateoperator:(${value[0].identityid})`
          }
        } else {
          if (config.IndexName == 'file') {
            sourceUser = `filemodifyoperator:(${value[0].identityid})`
          } else {
            sourceUser = `foldermodifyoperator:(${value[0].identityid})`
          }
        }
      }
      if ((key == 'filepath' || key == 'folderpath') && value.value && value.value.length > 0) {
        $clearpath(true)
        path = `(${key}:${value.value[0].folderid} AND NOT folderid:${value.value[0].folderid})`
      }
    }
    let SearchFieldsArray = params.SearchFields.split(',')
    if (config.IndexName == 'file') {
      if (!changedValues?.SearchFields || changedValues?.SearchFields?.length == 0 || changedValues?.SearchFields?.length == 3) {
        if (!SearchFieldsArray.includes('filetag')) {
          SearchFieldsArray.push('filetag')
        }
        if (!SearchFieldsArray.includes('filename')) {
          SearchFieldsArray.push('filename')
        }
        if (!SearchFieldsArray.includes('filecontent')) {
          SearchFieldsArray.push('filecontent')
        }
      } else {
        // 首先把三个元素都删除, 然后我有哪个就补哪个, splice会改变原数组, 所以不能将if写在一起
        const filetagIndex = SearchFieldsArray.findIndex(ele => ele == 'filetag')
        if (filetagIndex > -1) {
          SearchFieldsArray.splice(filetagIndex, 1)
        }
        const filenameIndex = SearchFieldsArray.findIndex(ele => ele == 'filename')
        if (filenameIndex > -1) {
          SearchFieldsArray.splice(filenameIndex, 1)
        }
        const filecontentIndex = SearchFieldsArray.findIndex(ele => ele == 'filecontent')
        if (filecontentIndex > -1) {
          SearchFieldsArray.splice(filecontentIndex, 1)
        }
        SearchFieldsArray = [...SearchFieldsArray, ...changedValues.SearchFields || []]
      }
    }

    if (changedValues?.SearchFields && changedValues?.SearchFields.length > 0) {
      $clearSearchFields(true)
    }
    const SearchFields = SearchFieldsArray.join(',')
    $buildInSearchParams({
      sourceUser,
      path
    })
    let fileSearchType = 'all'
    const topPersonalFolderId = engineProps.inbiz.userInfo.topPersonalFolderId
    if (fpath.includes('1')) {
      fileSearchType = 'enterprise'
    } else if (fpath.includes('7')) {
      fileSearchType = 'team'
    } else if (fpath.includes(String(topPersonalFolderId))) {
      fileSearchType = 'person'
    }

    $fileSearchType(fileSearchType)
    if (SearchFields) {
      $params({ ...params, PageIndex: 1, SearchFields })
    }
    const ftype = changedValues.filepath?.type || changedValues.folderpath?.type
    categoryLevel.current = -1
    $categoryData({})
    $selected([])
    belongCategoryRef.current = {
      ftype,
      folderid
    }
  }

  useImperativeHandle(ref, () => ({
    resetAll: (parentTopFolderId) => {
      form.resetFields()
      $pathValue({ value: '' })
      $clearSearchFields(false)
      $clearpath(false)
      setAutority(parentTopFolderId)
    },
    buildInForm: form,
    getData: (params) => categoryRef.current?.getData(params)
  }), [])
  const clearField = (key) => {
    form.resetFields([key])
    $clearSearchFields(false)
    $clearpath(false)
    onValuesChange()
    $pathValue({ value: '' })
  }
  const pathkey = config.IndexName == 'file' ? 'filepath' : 'folderpath'

  const BelongDirectoryComponent = <BelongDirectory
    params={params}
    configEvents={configEvents}
    topPersonalFolderId={engineProps.inbiz.userInfo.topPersonalFolderId}
    pathkey={pathkey}
    showTeam={showTeam}
    showPerson={showPerson}
    config={config}
    searchResult
    ref={categoryRef}
    searchEngineData={searchEngineData}
    getMetaSearchArr={getMetaSearchArr}
    buildInSearchParams={buildInSearchParams}
    pathValue={pathValue}
  />

  useEffect(() => {
    initmetadataitems()
    setAutority(searchEngineData.parentTopFolderId)
    const status = {
      default: 0,
      hideAll: 1,
      hideCreater: 2,
      hideModifyer: 3,
    }

    const filecreateoperator = searchEngineData?.SearchWhere?.includes('filecreateoperator');
    const filemodifyoperator = searchEngineData?.SearchWhere?.includes('filemodifyoperator');
    const foldercreateoperator = searchEngineData?.SearchWhere?.includes('foldercreateoperator');
    const foldermodifyoperator = searchEngineData?.SearchWhere?.includes('foldermodifyoperator');

    if ((filecreateoperator && filemodifyoperator) || (foldercreateoperator && foldermodifyoperator)) {
      $memberState(status.hideAll);
    } else if (filecreateoperator || foldercreateoperator) {
      $userType('2')
      $memberState(status.hideCreater);
    } else if (filemodifyoperator || foldermodifyoperator) {
      $userType('1')
      $memberState(status.hideModifyer);
    } else {
      $userType('0')
      $memberState(status.default);
    }

  }, [searchEngineData])

  const showCategory = useMemo(() => {
    if (config.showContents?.includes('belongCategory')) {
      const includesfolderpath = searchEngineData?.SearchWhere?.includes('folderpath')
      if (searchEngineData.isAdvanced && includesfolderpath) {
        return false
      }
      return true
    } else {
      return false
    }
  }, [config, searchEngineData])

  const clickUserType = (type: string) => {
    const value = form.getFieldValue('sourceuser')
    $userType(type)
    if (value && value.length > 0) {
      onValuesChange(type)
    }
  }

  return (
    <div className='buildInArea'>
      <ShowPlugin IndexCode={config.IndexCode} pluginName='SearchResultEngine.RightPlugin' />
      {
        (buildInkeys.every(ele => !config.showContents?.includes(ele)) && props?.list.length == 0) ? null :
          <Form onValuesChange={onValuesChange} form={form} >
            {showCategory && <>
              <FormItemTitle title={'SearchResultEngine.belongCategory'} config={config} showClear={clearpath} clearField={() => clearField(config.IndexName == 'file' ? 'filepath' : 'folderpath')} />
              <Form.Item
                name={config.IndexName == 'file' ? 'filepath' : 'folderpath'}
              >
                {BelongDirectoryComponent}
              </Form.Item>
            </>}
            {config.showContents?.includes('matchtype') && <>
              <FormItemTitle title={'SearchResultEngine.matchtype'} clearField={() => clearField('SearchFields')} config={config} showClear={clearSearchFields} />
              <Form.Item name='SearchFields'>
                <Checkbox.Group options={plainOptions} />
              </Form.Item>
            </>}
            {config.showContents?.includes('sourceUser') &&
              memberState != 1
              && <>
                <div className='sourceUser'>
                  <div style={{color: '#666'}}><TextWidget>SearchResultEngine.sourceUser</TextWidget>： </div>
                  <div>
                    {
                      memberState != 2 && memberState != 3 &&
                      <>
                        <span className={userType == '0' ? 'selectType' : ''} onClick={() => {
                          clickUserType('0')
                        }}><TextWidget>SearchResultEngine.whole</TextWidget></span>
                        <span> | </span>
                      </>
                    }

                    {
                      (memberState == 3 || memberState == 0) &&
                      <>
                        <span className={userType == '1' ? 'selectType' : ''} onClick={() => {
                          clickUserType('1')
                        }}><TextWidget>SearchResultEngine.createdBy</TextWidget></span>
                        {
                          memberState == 0 && (<span> | </span>)
                        }
                      </>
                    }

                    {
                      (memberState == 2 || memberState == 0) && (
                        <span className={userType == '2' ? 'selectType' : ''} onClick={() => {
                          clickUserType('2')
                        }}><TextWidget>SearchResultEngine.modifiedBy</TextWidget></span>
                      )
                    }
                  </div>
                </div>
                <Form.Item
                  name='sourceuser'
                >
                  <EformMemberSelect
                    inbiz={engineProps.inbiz}
                    multiple={false}
                    tabs={['user']}
                  />
                </Form.Item>
              </>}
          </Form>
      }
    </div>
  )
})
